//
//  ResevedListController.m
//  MetenEnglish
//
//  Created by rj-mayong on 14/12/2.
//  Copyright (c) 2014年 Shenzhen Securities Information Co., Ltd. All rights reserved.
//

#import "ResevedListController.h"
#import "CourseModel.h"
#import "ZCActionOnCalendar.h"
#import "Tools.h"


@interface ResevedListController () {
    UIBarButtonItem *_rightBarItem;
    NSUInteger _deleteIndex;
}

@end

@implementation ResevedListController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.title = @"待上课程";
    _reservedList = [[NSMutableArray alloc] initWithCapacity:10];
    
    _rightBarItem = [[UIBarButtonItem alloc] initWithTitle:@"导入日历"
                                                                style:UIBarButtonItemStyleDone
                                                               target:self
                                                               action:@selector(saveToCalendar)];
    _rightBarItem.accessibilityLabel = @"importCalendar";
    self.navigationItem.rightBarButtonItem = _rightBarItem;
    [_rightBarItem setEnabled:NO];
    
    // initialization refreshControl
    UIRefreshControl *refreshControl = [[UIRefreshControl alloc] init];
    [refreshControl addTarget:self action:@selector(refreshReservedList:) forControlEvents:UIControlEventValueChanged];
    self.refreshControl = refreshControl;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)refreshReservedList:(id)sender {
    [HttpManager share].isFresh = YES;
    [[HttpManager share] searchCourses:1];
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
//#warning Potentially incomplete method implementation.
    // Return the number of sections.
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
//#warning Incomplete method implementation.
    // Return the number of rows in the section.
    if (_reservedList.count != 0) {
        return _reservedList.count;
    }
    return 0;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *cellId = @"cellId";
    CourseCell *cell = [tableView dequeueReusableCellWithIdentifier:cellId];
    
    if (nil == cell) {
        cell = [[CourseCell alloc] initWithStyle:UITableViewCellStyleDefault
                                 reuseIdentifier:cellId
                                        cellType:CELL_RESERVEDLIST];
        [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
        cell.delegate = self;
    }
    
    if (_reservedList.count != 0) {
        [cell setCellContent:[_reservedList objectAtIndex:indexPath.row]];
    }
    
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 120.0f;
}

- (void)showCoursList:(NSArray *)courses {
    // clear the dirty data
    [_reservedList removeAllObjects];
    [_reservedList addObjectsFromArray:courses];
    
    // stop refreshing
    if (self.refreshControl.isRefreshing) {
        [self. refreshControl endRefreshing];
    }
    
    // refresh tableView;
    [self.tableView reloadData];
    [_rightBarItem setEnabled:YES];
}

#pragma mark - 点击“我要退课”回调
- (void)clickedCourseButton:(CourseModel *)courseModel {
    _deleteIndex = [_reservedList indexOfObject:courseModel];
    
    [[HttpManager share] setCancelCourseDelegate:self];
    [[HttpManager share] cancelReservedCourse:courseModel.courseId];
}


- (void)saveToCalendar {
    //首先删除以前的订课记录
    [self removeCalendarCourse];
    //导入服务器最新的订课记录
    for (CourseModel *model in _reservedList) {
        
        NSRange range = [model.time rangeOfString:@"("];
        NSString *startString = [model.time substringWithRange:NSMakeRange(0, range.location)];
        NSString *endString = [model.time substringWithRange:NSMakeRange(range.location + 6, 5)];
        NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
        [formatter setDateFormat:@"yyyy-MM-dd HH:mm"];
        NSDate *startDate = [formatter dateFromString:[NSString stringWithFormat:@"%@%@",startString,endString]];
        [ZCActionOnCalendar saveEventStartDate:startDate
                                       endDate:[startDate dateByAddingTimeInterval:60 * 60]
                                         alarm:-60  * 120   //提前两小时提醒
                                    eventTitle:EVENT_TITLE(model.name,model.time,model.teacher)
                                      location:model.address
                                    isReminder:YES];
    }
    [self showAlertView:@"订课记录已成功导入到日历!"];
}

- (void)removeCalendarCourse {
    
    EKEventStore *eventStore = [[EKEventStore alloc] init];
    NSArray *events = [ZCActionOnCalendar searchEventsWithEventStore:eventStore];
    
    for (EKEvent *event in events) {
        //如果标题不能截取成一个长度位3的数组,代表不是订课记录,不做任何处理
        NSArray *arr = [event.title componentsSeparatedByString:@"&^"];
        if (arr.count != 3) {
            continue;
        }
        NSError *error = nil;
        [eventStore removeEvent:event span:EKSpanFutureEvents error:&error];
    }
    [eventStore commit:nil];
}

- (void)showAlertView:(NSString *)message {
    UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:message
                                                        message:nil
                                                       delegate:self
                                              cancelButtonTitle:@"确定"
                                              otherButtonTitles:nil, nil];
    [alertView show];
}

#pragma mark - CancelCourseDelegate
- (void)cancelCourseResult:(id)result {
    BOOL isSuccess = [result boolValue];
    if (isSuccess) {
        [self showAlertView:@"退课成功!"];
        
        // delete the course which has been canceled in reservedArray
        [_reservedList removeObjectAtIndex:_deleteIndex];
        [self.tableView reloadData];
    }
    else {
        [self showAlertView:@"退课失败!"];
    }
}

@end
